package com.portal4kids.view;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.portal4kids.controller.FTPManager;

@WebServlet("/Upload")
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Upload() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		FTPManager ftp = new FTPManager();
		HttpSession session = request.getSession();
		String nazwaZdjecia = (String) session.getAttribute("album");
		System.out.println("Nazwa: " + nazwaZdjecia);
		String savePath = this.getServletConfig().getServletContext().getRealPath("");
        savePath = savePath + "/uploads/";
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        ftp.polaczZFTP();
        ftp.wybierzKatalogFTP("/portal4kids/");
        upload.setHeaderEncoding("utf-8");

        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            return;
        }

        Iterator<FileItem> it = fileList.iterator();
        String name = "";
        String extName = "";
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                name = item.getName();
                String type = item.getContentType();
                if (name == null || name.trim().equals("")) {
                    continue;
                }
                File saveFile = new File(savePath + name );
                
                try {
                    item.write(saveFile);
                    ftp.wrzucNaSerwer(saveFile, nazwaZdjecia);
                    
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

        }
        ftp.rozlaczZFTP();
        session.removeAttribute("album");
        response.sendRedirect("adminPanel.jsp");
        
	}

}
